package com.nolon.flange

import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatEditText
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.nolon.flange.adapter.SectionsPagerAdapter
import com.nolon.flange.databinding.ActivityAutoCalcBinding
import com.nolon.flange.extensions.toast
import com.nolon.flange.fragment.FlangeCalcFragment
import com.nolon.flange.fragment.FlangeExportFragment
import com.nolon.flange.fragment.FlangeOrderFragment
import com.nolon.flange.model.Project
import com.nolon.flange.repository.ProjectRepository
import com.nolon.flange.viewmodel.FlangeViewModel
import com.nolon.flange.viewmodel.FlangeViewModelFactory
import com.google.android.material.button.MaterialButton
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class FlangeActivity : AppCompatActivity() {
    private lateinit var _binding: ActivityAutoCalcBinding
    private val bd: ActivityAutoCalcBinding get() = _binding

    lateinit var flangeViewModel: FlangeViewModel
    private var isNewProject = true

    private val orderFragment by lazy { FlangeOrderFragment(this) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        _binding = ActivityAutoCalcBinding.inflate(layoutInflater)
        setContentView(bd.root)
        setSupportActionBar(bd.toolbar)
        supportActionBar?.apply {
            setHomeButtonEnabled(true)
            setDisplayHomeAsUpEnabled(true)
            title = getString(R.string.flange_activity_title)
        }

        isNewProject = intent.hasExtra(MainActivity.IS_NEW_PROJECT)
        val projectId = intent.getIntExtra(MainActivity.PROJECT_ID, -1)

        if (isNewProject || projectId == -1) {
            lifecycleScope.launch {
                val id = withContext(Dispatchers.IO) {
                    val projectRepository = ProjectRepository(application)
                    projectRepository.insertProject(Project(0, getString(R.string.unnamed_project)))
                }
                val viewModelFactory = FlangeViewModelFactory(application, id.toInt())
                flangeViewModel = ViewModelProvider(
                    this@FlangeActivity,
                    viewModelFactory
                ).get(FlangeViewModel::class.java)
                initView()
            }
        } else {
            val viewModelFactory = FlangeViewModelFactory(application, projectId)
            flangeViewModel = ViewModelProvider(
                this@FlangeActivity,
                viewModelFactory
            ).get(FlangeViewModel::class.java)
            initView()
        }
    }

    private fun initView() {
        val calcFragment = FlangeCalcFragment.newInstance(this@FlangeActivity)
        val exportFragment = FlangeExportFragment(this@FlangeActivity)
        val fragmentList =
            listOf<Fragment>(orderFragment, calcFragment, exportFragment)

        // Set up ViewPager and TabLayout
        val sectionsPagerAdapter =
            SectionsPagerAdapter(fragmentList, supportFragmentManager)
        bd.viewPager.apply {
            adapter = sectionsPagerAdapter
            offscreenPageLimit = 2
            bd.tabs.setupWithViewPager(this)
        }
    }

    override fun onBackPressed() {
        // 新项目没有法兰, 删除项目
        if (isNewProject && flangeViewModel.isEmpty) {
            flangeViewModel.removeProject()
            super.onBackPressed()
        }
        // 新项目有法兰, 要求输入项目名
        if (flangeViewModel.isNotEmpty && isNewProject) {
            val alertDialog = AlertDialog.Builder(this)
            val saveView = layoutInflater.inflate(R.layout.dialog_project_name, null)
            val btnCancel = saveView.findViewById<MaterialButton>(R.id.btnCancel)
            val btnConfirm = saveView.findViewById<MaterialButton>(R.id.btnConfirm)
            val editProjectName = saveView.findViewById<AppCompatEditText>(R.id.editProjectName)
            alertDialog.setView(saveView)
            val saveDialog = alertDialog.create()
            btnCancel.setOnClickListener {
                flangeViewModel.removeProject()
                saveDialog.dismiss()
                super.onBackPressed()
            }
            btnConfirm.setOnClickListener {
                val projectName = editProjectName.text.toString().trim()
                if (projectName == "") {
                    it.toast(R.string.require_project_name)
                    return@setOnClickListener
                }
                flangeViewModel.updateProject(projectName)
                saveDialog.dismiss()
                super.onBackPressed()
            }
            saveDialog.show()
        }
        // 旧项目有法兰
        if (flangeViewModel.isNotEmpty && !isNewProject) {
            super.onBackPressed()
        }
        // 旧项目没有法兰
        if (!flangeViewModel.isNotEmpty && !isNewProject) {
            toast(this, getString(R.string.deleted_for_empty_flange))
            flangeViewModel.removeProject()
            super.onBackPressed()
        }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            android.R.id.home -> {
                onBackPressed()
                setResult(RESULT_OK)
            }
            R.id.toolbarAddOrder -> {
                bd.tabs.getTabAt(0)?.select()
                orderFragment.openSheet()
            }
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onSupportNavigateUp(): Boolean {
        onBackPressed()
        setResult(RESULT_OK)
        return true
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        bd.toolbar.inflateMenu(R.menu.menu_flange)
        return true
    }

}